import serial
from binascii import unhexlify
import pymodbus.utilities as uti
import redis
import time
import statistics

if __name__ == '__main__':
    r = redis.Redis(db=0)
    # r.set('radar_1', 'off')     # dmesg | grep tty

    ser = serial.Serial('/dev/ttyLaser', 115200)
    ser.readline()

    distance_l = []

    while r.get('process_7').decode("utf-8") == 'on':
        result = ser.readline()
        if len(result) == 19:
            result = result[1:-2]

            checksum = result[-4:]
            data = result[:-4]

            try:
                if uti.computeCRC(unhexlify(data)) == int(checksum, 16):
                    distance = int(data[-4:], 16)

                        # distance_l.append(distance)
                    print(distance)
                    r.set('process_7_log', distance)

                    # r.set('radar_1_distance', int(distance))
                    if r.llen('distance_q') > 40:
                        r.lpop('distance_q')
                    r.rpush('distance_q', int(distance))
            except:
                pass
        else:
            time.sleep(0.5)
            distance_l = []

